package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
 * 定时检查订单情况
 * */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /*
     * 每分钟检查一次订单支付情况,将超时订单的支付状态设置为超时取消
     * */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processTimeOutOrder() {
        LocalDateTime time = LocalDateTime.now();
        log.info("定时处理超时订单:{}", time);
        LocalDateTime overTime = time.minusMinutes(15);
        //查询未支付且超时的订单
        List<Orders> list = orderMapper.findTimeOutOrder(Orders.PENDING_PAYMENT, overTime);
        //判断当前是否存在符合要求的订单
        if (list != null && list.size() > 0) {
            list.forEach(orders -> {
                //更新数据
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时,自动取消");
                orders.setCancelTime(time);
                orderMapper.update(orders);
            });
        }
    }


    /*
     * 每天凌晨一点检查一次订单完成情况,将已支付未完成订单设置为已完成
     * */
    @Scheduled(cron = "0 0 1 * * *")
    public void processDeliveryOrder() {
        LocalDateTime time = LocalDateTime.now();
        log.info("定时处理派送中状态订单:{}", time);
        LocalDateTime overTime = time.minusHours(1);
        //查询未支付且超时的订单
        List<Orders> list = orderMapper.findTimeOutOrder(Orders.DELIVERY_IN_PROGRESS, overTime);
        //判断当前是否存在符合要求的订单
        if (list != null && list.size() > 0) {
            list.forEach(orders -> {
                //更新数据
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }

    }
}
